package cn.javacart.jopencart.service.catalog.account;

import java.util.Date;

import cn.javacart.jopencart.kit.WebKit;
import cn.javacart.jopencart.model.Customer;
import cn.javacart.jopencart.model.CustomerLogin;

import com.jfinal.aop.Duang;
import com.jfinal.plugin.activerecord.Db;

/**
 * 用户账号service
 * @author farmer
 *
 */
public class AccountCustomerService {
	
	public final static AccountCustomerService ME = Duang.duang(AccountCustomerService.class);
	
	/**
	 * 尝试次数
	 * @param email
	 * @return
	 */
	public CustomerLogin getLoginAttempts(String email){
		return CustomerLogin.ME.findFirst("SELECT * FROM `joc_customer_login` WHERE email = ?", email);
	}
	/**
	 * 通过邮箱获取客户
	 * @param email
	 * @return
	 */
	public Customer getCustomerByEmail(String email){
		return Customer.ME.findFirst("SELECT * FROM joc_customer WHERE LOWER(email) = ?", email);
	}
	/**
	 * 添加尝试次数
	 * @param email
	 */
	public void addLoginAttempt(String email) {
		String remoteAddr = WebKit.getIp();
		CustomerLogin customerLogin = CustomerLogin.ME.findFirst("SELECT * FROM `joc_customer_login` WHERE email = ? and ip = ?", email , remoteAddr);
		if(customerLogin == null){
			new CustomerLogin().set("email", email).set("ip", remoteAddr).set("total", 1)
							.set("date_added", new Date()).set("date_modified", new Date()).save();
		}else{
			customerLogin.set("total", customerLogin.getInt("total")+1).set("date_modified", new Date()).update();
		}
	}
	/**
	 * 删除尝试次数
	 * @param email
	 */
	public void deleteLoginAttempts(String email) {
		Db.update("DELETE FROM `joc_customer_login` WHERE email = ?", email);
	}
	
}